import 'dart:async';
import 'package:flutter/material.dart';
import 'package:noway/DataModel.dart';
import 'package:noway/Hitokoto.dart';
import 'package:fluttertoast/fluttertoast.dart';
// main
void main() => runApp(  MyApp());

class MyApp extends StatelessWidget{

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Koto',
      home: ContentWidget()
    );
  }
}

class ContentWidget extends StatefulWidget{
  @override
  State<StatefulWidget> createState() {
    return   ContentWidgetState();
  }
}

class ContentWidgetState extends State<ContentWidget> {
  /**
   * data
   */
  List<Hitokoto> hitokotos = List.from(Iterable.empty());
  Text appBarTitle;
  FloatingActionButton floatingActionButton;
  @override
  void initState() {
    print('initState');
    appBarTitle =  Text(hitokotos.length.toString()+' koto');
    floatingActionButton =   FloatingActionButton(
      foregroundColor: Colors.white,
      child:   Icon(Icons.add),
        onPressed: (){ 
          refreshData(); 
    });
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: appBarTitle,
        centerTitle: true,
      ),
      drawer: Drawer(
        child: ListView(
          padding: EdgeInsets.zero,
          children: <Widget>[
            Material(
              child:InkWell(
                child:DrawerHeader(
                  child: Text('Hitoko Demo',
                  textAlign: TextAlign.start,
                  style: TextStyle(
                    fontSize: 24.0,
                    color: Colors.black54
                  ),),
                  decoration: BoxDecoration(
                    color: Colors.blue,
                    image:   DecorationImage(
                      fit: BoxFit.fill,
                      image: Image.network("https://soulofcinder.xyz/static/img/zexuejia_avatar.webp").image
                    )
                  ),
                ),
              )
            ),
            ListTile(
              title: Text('@author dqn',textAlign: TextAlign.right,),
              subtitle: Text(' r u a ！',textAlign: TextAlign.right,),
              onTap: () {  
              },
            )
          ],
        ),
      ),
      body: ListView(
        children: hitokotos.map((info){
          return buildListTile(context, info);
        }).toList(),  
      ),
      floatingActionButton: floatingActionButton
    );
  }
  /**
   * list view adapter
   */
  Widget buildListTile(BuildContext buildContext,Hitokoto hitokoto){
    return GestureDetector(
        child:Card(
          elevation: 2.0,
          child: Column(
            children: <Widget>[
              ListTile(
                leading: Icon(Icons.sms,),
                title: Text(hitokoto.fromWhere),
                subtitle: Text(hitokoto.koto),
              ),
              Container(
                
                child: Text('by '+hitokoto.creator),
                alignment: Alignment.bottomRight,
                padding: EdgeInsets.fromLTRB(8.0, 0.0, 8.0, 4.0)
              )
            ],
          ),
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.all(Radius.circular(8.0)),
          ),
        ), 
        onLongPress: (){ removeData(hitokoto); },
      );
  }
  /**
   * 删除某个
   */
  void removeData(Hitokoto info){
      setState(() {
        Fluttertoast.showToast(
            msg: "删除" + hitokotos.indexOf(info).toString(),
            toastLength: Toast.LENGTH_SHORT,
            gravity: ToastGravity.CENTER,
            timeInSecForIos: 1,
            bgcolor: "#e74c3c",
            textcolor: '#ffffff'
        );  
        hitokotos.removeAt(hitokotos.indexOf(info));
        appBarTitle =  Text(hitokotos.length.toString()+' kotos');
      });
    }
    /**
     * 获取koto
     */
  void refreshData(){
    setState(() {
          appBarTitle = Text("获取中...",textDirection: TextDirection.ltr,);
        });
    var url = "https://soulofcinder.xyz/hitokoto";
    GetInfo getInfo =   GetInfo();
    Future<Hitokoto> futureKoto = getInfo.getDataFromNet(url);
    futureKoto.then((onValue){
      bool alreadyIn = Iterable
        .castFrom(hitokotos)
        .any((test){
          return test.id == onValue.id;
        });
      if (alreadyIn){
        print("already in list");
        Fluttertoast.showToast(
          msg: "已存在此条",
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.CENTER,
          timeInSecForIos: 1,
          bgcolor: "#e74c3c",
          textcolor: '#ffffff'
        );
        appBarTitle =  Text(hitokotos.length.toString()+' kotos');
      }else{
        print(onValue.koto);
        setState(() {
          hitokotos.insert(0, onValue);
          appBarTitle =  Text(hitokotos.length.toString()+' kotos');
        });
      }
    });
  }
}
